package com.shop.shoporder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.shop.shoporder.common.HttpPost;
import com.shop.shoporder.entity.HttpRequestConfig;
import com.shop.shoporder.entity.Newuserorder;
import com.shop.shoporder.entity.RedisUserNo;
import com.shop.shoporder.entity.Store;
import com.shop.shoporder.entity.order.Cart;
import com.shop.shoporder.entity.order.OrderSettlement;
import com.shop.shoporder.mapper.NewuserorderMapper;
import com.shop.shoporder.mapper.StoreMapper;
import com.shop.shoporder.mapper.order.CartMapper;
import com.shop.shoporder.mapper.order.OrderSettlementMapper;
import com.shop.shoporder.service.OrderSettlementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("OrderSettlementService")
public class OrderSettlementServiceImpl implements OrderSettlementService {

    @Autowired
    OrderSettlementMapper orderSettlementMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    NewuserorderMapper newuserorderMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StoreMapper storeMapper;

    @Override
    public Boolean selectSettlement() {
        try {
            //读取没结算的订单
            System.out.println("读取没结算的订单");
            List<OrderSettlement> orderSettlementList = orderSettlementMapper.selectSettlement();
            if (orderSettlementList != null) {
//                for (OrderSettlement orderSettlement : orderSettlementList) {
//                    Settlement(orderSettlement);
//                }
                for(int i=0;i<orderSettlementList.size();i++)
                {
                    OrderSettlement orderSettlement = orderSettlementList.get(i);
                    Settlement(orderSettlement);
                    //break;
                }
            }
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    @Transactional
    public boolean Settlement(OrderSettlement orderSettlement) {
        try {

            //开始结算订单
            System.out.println("开始结算订单:" + orderSettlement.getOrderNo());
            //读取用户信息

            int shareId = 0;//分享ID
            int rankId =  0; //等级ID
            int ownerid = 0;//店主ID
            int veraId =  0; //芦荟屋

            String msgCode = "";

//                String res = HttpPost.GetMod(HttpRequestConfig.userServerUrl, "User/SelfShare", "id=" + orderSettlement.getUsernoId());
//                JSONObject resJSON = JSONObject.parseObject(res);
//                msgCode = resJSON.get("code").toString();
//                if (msgCode.equals("000000")) {//如果失败
//                    String data = resJSON.get("data").toString();
//                    System.out.println(data);
//                    JSONObject resDataJSON = JSONObject.parseObject(data);
//                    try {
//                        shareId = Integer.parseInt(resDataJSON.get("share").toString());
//                        rankId = Integer.parseInt(resDataJSON.get("rankId").toString());
//                        if (Boolean.parseBoolean(resDataJSON.get("vera").toString())) {
//                            veraId = orderSettlement.getUsernoId();
//                        }
//                    } catch (Exception ex) {
//
//                    }
//                } else {
//                    bl = false;
//                }

            System.out.println("读取用户信息:"+"ID" + orderSettlement.getUsernoId());
            /*读取用户信息*/
            RedisUserNo redisUserNo = JSON.parseObject(redisTemplate.opsForValue().get("ID" + orderSettlement.getUsernoId()).toString(), new TypeReference<RedisUserNo>() {
            });
            if (redisUserNo != null) {
                shareId = redisUserNo.getShare();
                rankId = redisUserNo.getRankId();
                if (redisUserNo.getVera()) {
                    veraId = orderSettlement.getUsernoId();
                }
            } else {
                return false;
            }

            int classify = 4;

            if (rankId > 3 && rankId < 7) {
                classify = 1;
                ownerid = orderSettlement.getUsernoId();
            }

            if(orderSettlement.getGuigeId()==1536 || orderSettlement.getGuigeId()==1537 || orderSettlement.getGuigeId()==1614
                    || orderSettlement.getGuigeId()==1539 || orderSettlement.getGuigeId()==1540 || orderSettlement.getGuigeId()==1541
                    || orderSettlement.getGuigeId()==1542 || orderSettlement.getGuigeId()==1608 || orderSettlement.getGuigeId()==1609
                    || orderSettlement.getGuigeId()==1543 || orderSettlement.getGuigeId()==1615 || orderSettlement.getGuigeId()==1616)
            {
                classify = 1;
            }


            System.out.println("分享赚");
            /*分享赚161*/
            if (shareId > 0 && orderSettlement.getShare()>0) {
                String shareRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=" + classify + "&type=161&state=1&userId=" + shareId + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + orderSettlement.getShare() + "&remark=分享赚" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
                JSONObject shareResJSON = JSONObject.parseObject(shareRes);
                msgCode = shareResJSON.get("code").toString();
                if (!msgCode.equals("000000")) {//如果失败
                    return false;
                }
            }

            System.out.println("消费赠");
            //消费赠162
            if(orderSettlement.getConsumption()>0) {
                String xonsumptionRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=4&type=162&state=1&userId=" + orderSettlement.getUsernoId() + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + orderSettlement.getConsumption() + "&remark=消费赠" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
                JSONObject xonsumptionResJSON = JSONObject.parseObject(xonsumptionRes);
                msgCode = xonsumptionResJSON.get("code").toString();
                if (!msgCode.equals("000000")) {//如果失败
                    return false;
                }
            }

//            System.out.println("运营部");
//            //运营部163
//
//            System.out.println("运营商");
//            //运营商164
//            String operationsRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=1&type=164&state=0&userId=" + orderSettlement.getOperator() + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + orderSettlement.getConsumption() + "&remark=运营商" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
//            JSONObject operationsResJSON = JSONObject.parseObject(operationsRes);
//            msgCode = operationsResJSON.get("code").toString();
//            if (!msgCode.equals("000000")) {//如果失败
//                return false;
//            }
//
//            System.out.println("随机红包："+orderSettlement.getRedEnvelope());
//            //随机红包163
//            String goodsName = orderSettlement.getNameSort();
//            Double redEnvelope = orderSettlement.getRedEnvelope() / 100;
//            List<Newuserorder> newuserorderList = newuserorderMapper.selectList();
//            for (int i = 0; i < newuserorderList.size(); i++) {
//                String redRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=" + classify + "&type=163&state=0&userId=" + newuserorderList.get(i).getUserId() + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + redEnvelope + "&remark=" + goodsName + " 发来的红包");
//
////                JSONObject redResJSON = JSONObject.parseObject(redRes);
////                msgCode = redResJSON.get("code").toString();
////                if (!msgCode.equals("000000")) {//如果失败
////                    return false;
////                }
//            }

            double owner = 0.00;
            double ownerRed = 0.00;

            System.out.println("rankId:" + rankId);

            System.out.println("店主差价");
            /*店主差价181*/
            if (ownerid == 0) {
//                String ownerRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "User/getOwner", "id=" + shareId);
//                JSONObject ownerResJSON = JSONObject.parseObject(ownerRes);
//                msgCode = ownerResJSON.get("code").toString();
//                if (msgCode.equals("000000")) {//如果成功
//                    String data = ownerResJSON.get("data").toString();
//                    if (!data.equals("0")) {//如果有店主
//                        JSONObject resDataJSON = JSONObject.parseObject(data);
//                        try {
//                            ownerid = Integer.parseInt(resDataJSON.get("id").toString());
//                            rankId = Integer.parseInt(resDataJSON.get("rankId").toString());
//                            if (Boolean.parseBoolean(resDataJSON.get("vera").toString())) {
//                                veraId = ownerid;
//                            }
//                        } catch (Exception ex) {
//
//                        }
//                    }
//                }

                System.out.println("店主差价");
                /*查找店主*/
                System.out.println("查找店主:"+"ID" + shareId);

                RedisUserNo redisUserNo1=null;

                try {
                    String userNoJson = redisTemplate.opsForValue().get("ID" + shareId).toString();
                    System.out.println("JSON:"+userNoJson);
                    redisUserNo1 = JSON.parseObject(userNoJson, new TypeReference<RedisUserNo>() {
                    });
                }catch (Exception ex)
                {
                    System.out.println("读取缓存错误!!");
                }

                while (redisUserNo1 != null) {
                    if (redisUserNo1.getShare() < 1) {
                        break;
                    }
                    System.out.println("rankId:"+redisUserNo1.getRankId());
                    if (redisUserNo1.getRankId() > 3 && redisUserNo1.getRankId() < 7) {
                        ownerid = redisUserNo1.getId();
                        rankId = redisUserNo1.getRankId();
                        break;
                    } else {
                        System.out.println("查找店主:"+"ID" + redisUserNo1.getShare());
                        redisUserNo1 = JSON.parseObject(redisTemplate.opsForValue().get("ID" + redisUserNo1.getShare()).toString(), new TypeReference<RedisUserNo>() {
                        });
                        try {
                            String userNoJson = redisTemplate.opsForValue().get("ID" + redisUserNo1.getShare()).toString();
                            System.out.println("循环:"+userNoJson);
                            redisUserNo1 = JSON.parseObject(userNoJson, new TypeReference<RedisUserNo>() {
                            });
                        }catch (Exception ex)
                        {
                            System.out.println("A读取缓存错误!!");
                        }
                    }
                }

            }
            System.out.println("A店主ID:"+ownerid);
            System.out.println("A店主等级:"+rankId);
            if (ownerid > 0) {
                if (rankId == 3) {
                    owner = orderSettlement.getPrice() - orderSettlement.getOwner1();
                } else if (rankId == 4) {
                    owner = orderSettlement.getPrice() - orderSettlement.getOwner2();
                } else if (rankId == 5) {
                    owner = orderSettlement.getPrice() - orderSettlement.getOwner3();
                } else if (rankId == 6) {
                    owner = orderSettlement.getPrice() - orderSettlement.getOwner4();
                }

                //需要减去店主红包
                ownerRed = 0;

//                System.out.println("店主红包");
//                //店主红包166
//                Store store = storeMapper.selectStoreInfo(ownerid);
//                if(store!=null) {
//                    if (store.getWelfare() > 0) {
//                        ownerRed = (owner * store.getWelfare()) / (100 * 2);
//                        System.out.println("店主红包F");
//                        /*店主红包166*/
//                        if (shareId > 0) {
//                            String shareRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=" + classify + "&type=166&state=0&userId=" + shareId + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + ownerRed + "&remark=店主红包" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
//                            JSONObject shareResJSON = JSONObject.parseObject(shareRes);
//                            msgCode = shareResJSON.get("code").toString();
//                            if (!msgCode.equals("000000")) {//如果失败
//                                return false;
//                            }
//                        }
//
//                        System.out.println("店主红包X");
//                        //店主红包166
//                        String xonsumptionRes1 = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=" + classify + "&type=166&state=0&userId=" + orderSettlement.getUsernoId() + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + ownerRed + "&remark=店主红包" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
//                        JSONObject xonsumptionResJSON1 = JSONObject.parseObject(xonsumptionRes1);
//                        msgCode = xonsumptionResJSON1.get("code").toString();
//                        if (!msgCode.equals("000000")) {//如果失败
//                            return false;
//                        }
//
//                    }
//                }

                System.out.println("店主差价");
                /*店主差价*/
                if(owner>0) {
                    owner = owner - (ownerRed * 2);
                    String ownerRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=1&type=165&state=0&userId=" + ownerid + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + owner + "&remark=店主结算" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
                    JSONObject ownerResJSON = JSONObject.parseObject(ownerRes);
                    msgCode = ownerResJSON.get("code").toString();
                    if (!msgCode.equals("000000")) {//如果失败
                        return false;
                    }
                }
            }

            System.out.println("返代金券");
            //返代金券167
            if(orderSettlement.getOwnerCommission()>0)
            {
                String ownerRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=3&type=167&state=1&userId=" + orderSettlement.getUsernoId() + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + orderSettlement.getOwnerCommission() + "&remark=活动返" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
                JSONObject ownerResJSON = JSONObject.parseObject(ownerRes);
                msgCode = ownerResJSON.get("code").toString();
                if (!msgCode.equals("000000")) {//如果失败
                    return false;
                }
            }

            System.out.println("返消费券");
            //返消费券168
            if(orderSettlement.getActivityCommission()>0)
            {
                String ownerRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=4&type=168&state=1&userId=" + orderSettlement.getUsernoId() + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + orderSettlement.getActivityCommission() + "&remark=活动返" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
                JSONObject ownerResJSON = JSONObject.parseObject(ownerRes);
                msgCode = ownerResJSON.get("code").toString();
                if (!msgCode.equals("000000")) {//如果失败
                    return false;
                }
            }

            System.out.println("芦荟屋差价");

//            //芦荟屋差价182
//            if (veraId == 0) {
//                String veraRes = HttpPost.GetMod(HttpRequestConfig.userServerUrl, "/User/getVera", "id=" + shareId);
//                JSONObject veraResJSON = JSONObject.parseObject(veraRes);
//                msgCode = veraResJSON.get("code").toString();
//                if (msgCode.equals("000000")) {//如果成功
//                    String data = veraResJSON.get("data").toString();
//                    if (!data.equals("0")) {//如果有芦荟屋
//                        JSONObject resDataJSON = JSONObject.parseObject(data);
//                        try {
//                            veraId = Integer.parseInt(resDataJSON.get("id").toString());
//                        } catch (Exception ex) {
//
//                        }
//                    }
//                }
//
//
//                if (veraId > 0) {
//                    double vera = orderSettlement.getOwner4() - orderSettlement.getAloeVeraShop();
//                    String veraRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=4&type=165&userId=" + ownerid + "&UID=" + orderSettlement.getUsernoId() + "&amount=" + owner + "&remark=芦荟屋结算" + orderSettlement.getOrderNo() + "S" + orderSettlement.getGuigeId());
//                    JSONObject veraResJSON = JSONObject.parseObject(veraRes);
//                    msgCode = veraResJSON.get("code").toString();
//                    if (!msgCode.equals("000000")) {//如果失败
//                        throw new RuntimeException();
//                    }
//                }
//
//            }

            //合开差价183

//            //供货商191
//            String supplierRes = HttpPost.GetMod(requestConfig.getFinaceServerUrl(),"/Finace/Add", "classify=4&type=191&userId=" + orderSettlement.getSupplierId() + "&UID="+ orderSettlement.getUsernoId() + "&amount=" + (orderSettlement.getSupplierPrice()-orderSettlement.getRedEnvelope()) + "&remark=供货商" + orderSettlement.getOrderNo()+"S"+orderSettlement.getGuigeId());
//            JSONObject supplierResJSON = JSONObject.parseObject(supplierRes);
//            msgCode = supplierResJSON.get("code").toString();
//            if (!msgCode.equals("000000")) {//如果失败
//                throw new RuntimeException();
//            }

            //业绩

            //活跃值

            //

            /*更新购物车结算状态*/
            Cart cart = new Cart();
            cart.setCartId(orderSettlement.getCartId());
            cart.setSettlement(1);
            cartMapper.updateByPrimaryKeySelective(cart);

            /*添加订单到100排序*/

            return true;
        } catch (Exception ex) {
            //throw new RuntimeException();
            return false;
        }
    }

    @Override
    public Boolean keepRedisUser() {
        //读取上一次到到什么地方了
        int maxid = 0;
        try {
            maxid = Integer.parseInt(redisTemplate.opsForValue().get("userjsmaxid").toString());
        } catch (Exception ex) {
        }

       // System.out.println("maxid:" + maxid);
        return true;
    }
}
